package top.fongs.spring_security_jwt.web.filters.once_per_request;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import top.fongs.spring_security_jwt.domain.entity.users.user_detail.UserDetail;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class AppOncePerRequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws ServletException, IOException {


        // 模拟数据， 正常逻辑是解析jwt-token，获取角色信息，填充GrantedAuthority

        UserDetail userDetail = new UserDetail( mapToGrantedAuthorities( Collections.singletonList( "ROLE_ADMIN" ) ) );
        logger.error( "<doFilterInternal>" );
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetail, null, userDetail.getAuthorities( ) );
        SecurityContextHolder.getContext( ).setAuthentication( usernamePasswordAuthenticationToken );

        chain.doFilter( request, response );
    }

    private static List< GrantedAuthority > mapToGrantedAuthorities( List< String > authorities ) {
        return authorities.stream( )
                .map( SimpleGrantedAuthority::new )
                .collect( Collectors.toList( ) );
    }
}
